package com.example.demo.controller.admin;


import com.example.demo.dao.CustomMapper;
import com.example.demo.entity.Role;
import com.example.demo.entity.User;
import com.example.demo.pojo.BSResult;
import com.example.demo.service.CustomService;
import com.example.demo.service.RoleService;
import com.example.demo.service.UserService;
import com.example.demo.utils.BSResultUtils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@RequiresPermissions("user-manage")
@RequestMapping("/admin/user")
@Controller
public class AdminUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private CustomService customService;

    @RequestMapping("/logout")
    public String adminLogOut(){

        SecurityUtils.getSubject().logout();
        return "redirect:/admin/index";
    }

    @RequestMapping("/echo/{userId}")
    @RequiresPermissions(value="user-edit")
    public String adminUserEcho(@PathVariable("userId")Integer userId,Model model){

        User user=userService.findUserById(userId);
        List<Role> allRoles=roleService.findAllRoles();
        List<Role> userRoles=customService.findRoleByUserId(userId);

        model.addAttribute("user",user);
        model.addAttribute("userRoles",userRoles);
        model.addAttribute("allRoles",allRoles);
        return "/admin/user/edit";
    }

    @RequestMapping("/list")
    @RequiresPermissions(value="user-list")
    public String adminUserList(Model model){

       model.addAttribute("users",userService.findAllUsers());

        return "/admin/user/list";
    }

    @RequestMapping("/toAddition")
    public String adminAddUser(Model model){
        List<Role> allRoles=roleService.findAllRoles();
        model.addAttribute("allRoles",allRoles);
        return "/admin/user/add";
    }


    @RequestMapping("/addition")
    public String addUser(User user,int[] roleIds){

        User newUser=userService.addUser(user);
        roleService.updateRole_User(user.getUserId(),roleIds);

        return "forward:list";
    }

    @RequestMapping("/deletion/{userId}")
    @ResponseBody
    public BSResult delete(@PathVariable(value = "userId")int userId){
       try {
           roleService.deleteRole_User(userId);
           userService.deleteById(userId);
           return BSResultUtils.build(200,"删除成功！刷新后即可看到刷新结果");
       }catch(Exception e){
           e.printStackTrace();
           return BSResultUtils.build(404,"删除失败，请重新尝试！");
       }

    }



    @RequestMapping("/update")
    public String update(User user,int[] roleIds,Model model){


        User originalUser=userService.findUserById(user.getUserId());

        try{
            if(user.getPassword()!="" && ! user.getPassword().equals(originalUser.getPassword())){
                String newPwd= DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
                user.setPassword(newPwd);
            }

            BSResult bsResult=userService.updateUser(user);

            if(bsResult.getCode()==200)
                model.addAttribute("saveMsg","更改信息成功！");

            if(roleIds!=null){
                roleService.deleteRole_User(user.getUserId());
                roleService.updateRole_User(user.getUserId(),roleIds);
            }

        }catch(Exception e){

        }
return "forward:/admin/user/echo/"+user.getUserId();
    }



}
